package com.gs.api.util.video.parse.pipixia;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.gs.api.util.video.parse.ParseConstant;
import com.gs.api.util.video.parse.ParseUtil;
import com.gs.api.util.video.parse.vo.VideoVo;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.util.List;

/**
 * @author guoyunfei on 2022/4/12 10:48
 * @className PiPiXiaApp
 * @description TODO 皮皮虾短视频
 * @Version 1.0
 */
public class PiPiXiaApp {

    /**
     * 皮皮虾
     * @param url
     * @return
     * @throws IOException
     */
    public static VideoVo pipixiaParseUrl(String url) throws IOException {

        VideoVo videoVo = new VideoVo();

        // 重定向地址
        String uuu = HttpUtil.createGet(url).addHeaders(ParseUtil.headers()).execute().header("Location");

        String itemId = uuu.split("https://h5.pipix.com/item/")[1].substring(0, 19);

        url="https://is.snssdk.com/bds/item/detail/?app_name=super&aid=1319&item_id="+itemId;

        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        Response response = okHttpClient.newCall(request).execute();
        String result=response.body().string();

        JSONObject jsonObject = JSONObject.parseObject(result);

        JSONObject data = jsonObject.getJSONObject("data").getJSONObject("data");

        String item_type = data.getString("item_type");

        videoVo.setCopywriting(data.getJSONObject("share").getString("title"));
        videoVo.setType("1".equals(item_type) ? ParseConstant.PARSE_IMAGES : ParseConstant.PARSE_VIDEO);

        //item_type 1 图片 2视频
        if("1".equals(item_type)){
            JSONArray multi_image = data.getJSONObject("note").getJSONArray("multi_image");

            List<String> images = Lists.newArrayList();
            for (int i = 0; i < multi_image.size(); i++) {
                String imageSrc = multi_image.getJSONObject(i).getJSONArray("download_list").getJSONObject(0).getString("url");
                images.add(imageSrc);
            }
            videoVo.setImages(images);

        }else{
            String cover_image = data.getJSONObject("video").getJSONObject("cover_image").getJSONArray("url_list")
                    .getJSONObject(0).getString("url");

            //视频地址
            String videoSrc = data.getJSONObject("video").getJSONObject("video_fallback").getJSONArray("url_list")
                    .getJSONObject(0).getString("url");

            videoVo.setVideoSrc(videoSrc);
            videoVo.setCoverSrc(cover_image);
        }
        System.out.println(videoVo.toString());

        return videoVo;
    }



}
